package com.example.project8
import android.content.Intent
import android.os.Bundle
import android.widget.ArrayAdapter
import android.widget.ListView
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import java.io.BufferedReader
import java.io.InputStreamReader
import kotlin.concurrent.thread
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main1)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
        thread {
            val cityCode = readFileFromRaw(R.raw.citycode)
            val gson = Gson()
            val CityType = object : TypeToken<List<CityItem>>() {
            }.type
            var cities : List<CityItem> = gson.fromJson(cityCode, CityType)
            cities = cities.filter { it.city_code.isNotBlank() }
            runOnUiThread{
                val adapter = ArrayAdapter<CityItem>(
                    this,
                    android.R.layout.simple_list_item_1,
                    cities
                )
                val listView = findViewById<ListView>(R.id.listView)
                listView.adapter = adapter
                listView.setOnItemClickListener{_,_, position, _ ->
                    val city = cities[position]
                    val intent = Intent(this, MainActivity2::class.java)
                    intent.putExtra("city", city.city_code)
                    startActivity(intent)
                }
            }
        }
    }
    fun readFileFromRaw(rawName: Int): String? {
        try {
            val inputReader = InputStreamReader(resources.openRawResource(rawName))
            val bufReader = BufferedReader(inputReader)
            var line: String? = ""
            var result: String? = ""
            while (bufReader.readLine().also({ line = it }) != null) {
                result += line
            }
            return result
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return ""
    }
}